package com.lucene.service;

import com.lucene.model.Project;
import com.lucene.utils.Utils;
import com.lucene.wmd4j.WordMovers;
import org.apache.log4j.Logger;
import org.deeplearning4j.models.embeddings.loader.WordVectorSerializer;
import org.deeplearning4j.models.embeddings.wordvectors.WordVectors;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by zhangzhen on 12/10/2017.
 */
@Service("computeService")
public class ComputeService {

    private static Logger logger = Logger.getLogger(ComputeService.class);

    private WordMovers wm;

    public ComputeService(String w2vPath) throws IOException{
        WordVectors vectors = WordVectorSerializer.loadTxtVectors(new FileInputStream(w2vPath),true);
        this.wm = WordMovers.Builder().wordVectors(vectors).build();

    }

    public ComputeService(WordMovers wm) {
        this.wm = wm;
    }

    public ComputeService() {
    }

    public WordMovers getWm() {
        return wm;
    }

    public void setWm(WordMovers wm) {
        this.wm = wm;
    }

    public double distance(String[] s1, String[] s2){
        return wm.distance(s1,s2);
    }

    public double cosDistance(String[] s1, String[] s2){
        return wm.cosDistance(s1,s2);
    }

    public void similarity(List<Project> candidates, String query){

        String[] qs = Utils.getSegments(query);
        Collections.sort(candidates,new Comparator(){
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Project && o2 instanceof Project){
                    double d1 = distance(((Project) o1).getDescriptions(),qs);
                    double d2 = distance(((Project) o2).getDescriptions(),qs);
                    if(d1-d2>0.000001)
                        return 1;
                    else if (d1-d2 < 0.000001)
                        return -1;
                }
                return 0;
            }
        });
    }

    /**
     * 文本词向量累加,余弦距离
     * @param candidates
     * @param query
     */
    public void consSimilarity(List<Project> candidates, String query){

        String[] qs = Utils.getSegments(query);
        Collections.sort(candidates,new Comparator(){
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Project && o2 instanceof Project){
                    double d1 = cosDistance(((Project) o1).getDescriptions(),qs);
                    double d2 = cosDistance(((Project) o2).getDescriptions(),qs);
                    if(d1-d2>0.000001)
                        return -1;
                    else if (d1-d2 < 0.000001)
                        return 1;
                }
                return 0;
            }
        });
    }
}
